package com.icesoft.xsnow.common.security.config;

import com.icesoft.xsnow.common.core.constant.SecurityConstants;
import com.icesoft.xsnow.common.security.component.HackerUserProperties;
import com.icesoft.xsnow.common.security.component.PermitAllUrlProperties;
import com.icesoft.xsnow.common.security.component.ResourceAuthExceptionEntryPoint;
import com.icesoft.xsnow.common.security.component.XsnowAccessDeniedHandler;
import com.icesoft.xsnow.common.security.oauth.component.XsnowUserAuthenticationConvert;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @program: xsnow
 * @description: 资源配置类
 * 1. 支持remoteTokenServices 负载均衡
 * 2. 支持 获取用户全部信息
 * @author: xuefeng.gao
 * @create: 2019-05-13 14:25
 **/
@Slf4j
@Configuration
@ConditionalOnMissingBean(name=SecurityConstants.RESOURCE_SERVER_CONFIGURER)
@ComponentScan("com.icesoft.xsnow.common.security")
public class XsnowResourceServerConfiguration extends ResourceServerConfigurerAdapter{

    @Autowired
    protected RemoteTokenServices remoteTokenServices;
    @Autowired
    PermitAllUrlProperties permitAllUrlProperties;
    @Autowired
    HackerUserProperties hackerUserProperties;
    @Autowired
    XsnowAccessDeniedHandler accessDeniedHandler;
    @Autowired
    ResourceAuthExceptionEntryPoint authExceptionEntryPoint;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new XsnowUserAuthenticationConvert();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        resources.tokenServices(remoteTokenServices);
        //自定义异常
        resources.authenticationEntryPoint(authExceptionEntryPoint)
                    .accessDeniedHandler(accessDeniedHandler);
    }

    /**
     * 默认的配置，对外暴露
     *
     * @param httpSecurity
     */
    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) throws Exception {
        //允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        //允许开启匿名用户
        if(hackerUserProperties.isEnabled()){
            httpSecurity.anonymous().authorities(SecurityConstants.ROLE_USER_ANONYMOUS);
        }
        //设置忽略权限URL
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        permitAllUrlProperties.getIgnoreUrls()
                .forEach(url -> registry.antMatchers(url).permitAll());
        //设置其他请求均需认证
       // registry.anyRequest().authenticated();
        //禁止csrf
        httpSecurity.csrf().disable();

    }


    //-------------------------------------------------------------------------
    @Bean
    @Primary
    @LoadBalanced
    public RestTemplate lbRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) {
                    super.handleError(response);
                }
            }
        });
        return restTemplate;
    }

}
